package com.example.firstassignment;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BMI extends Activity {
	
	private TextView display;
	private EditText lenghtInput, weightInput; 
	private Button resetButton, calculateButton;
	
	private AlertDialog alert;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bmi);
		
		display = (TextView)findViewById(R.id.BMIdisplay);
		
		lenghtInput = (EditText)findViewById(R.id.lenghtInput);
		weightInput = (EditText)findViewById(R.id.weightInput);
				
		resetButton = (Button)findViewById(R.id.buttonReset);
		resetButton.setOnClickListener(new buttonClick());
		calculateButton = (Button)findViewById(R.id.buttonCalculate);
		calculateButton.setOnClickListener(new buttonClick());
		
		alert = setup_alert();
	
	}
	private class buttonClick implements View.OnClickListener {
		public void onClick(View v){
			if( v == calculateButton){
				calculateBMI(); /* Calculates your BMI */
			}
			if( v == resetButton ){
				display.setText(getResources().getString(R.string.yourBMI));
				lenghtInput.setText("");
				weightInput.setText("");
			}
		}
	}
	
	private void calculateBMI(){
		double 	yourBMI = 0,
				yourLenght = 1, 
				yourWeight = 1;		
		try{
			yourLenght = Integer.parseInt(lenghtInput.getText().toString().trim());
			yourWeight = Integer.parseInt(weightInput.getText().toString().trim());	
			
			if( ( yourWeight > 300 ) || ( yourLenght > 300 ) ){
				alert.show();
			} else {
				yourBMI = (yourWeight / ((yourLenght/100) * (yourLenght/100)));
				yourBMI = Math.round(yourBMI);
				display.setText(getResources().getString(R.string.yourBMI)+yourBMI);
			}
		}
		catch(NumberFormatException nfe){
			alert.show();
		}
	}
	
    /* AlertDialog Setup and Handling */
    private AlertDialog setup_alert() {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getResources().getString(R.string.resonableNumber));
        builder.setCancelable(false);
        builder.setTitle(getResources().getString(R.string.enterNumber));
        builder.setPositiveButton(getResources().getString(R.string.done), new DialogDone());
        return builder.create();
    }
    
    private class DialogDone implements DialogInterface.OnClickListener {
    	public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    }

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}

}
